import 'package:flutter/material.dart';
import 'package:two_dimensional_scrollables/two_dimensional_scrollables.dart';

class InfiniteTablePage extends StatefulWidget {
  const InfiniteTablePage({super.key});

  @override
  State<InfiniteTablePage> createState() => _InfiniteTablePageState();
}

class _InfiniteTablePageState extends State<InfiniteTablePage> {
  int? _rowCount;
  int? _columnCount;

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('双向滑动控件'),
      ),
      body: Padding(
        padding: const EdgeInsets.symmetric(horizontal: 50.0),
        child: TableView.builder(
          mainAxis: Axis.horizontal,
          cellBuilder: _buildCell,
          columnCount: _columnCount,
          columnBuilder: _buildSpan,
          rowCount: _rowCount,
          rowBuilder: _buildSpan,
        ),
      ),
      persistentFooterAlignment: AlignmentDirectional.center,
      persistentFooterButtons: [
        Text(
          'Column count is ${_columnCount == null ? 'infinite' : '50  '}',
          style: const TextStyle(fontStyle: FontStyle.italic),
        ),
        FilledButton(
            onPressed: () {
              setState(() {
                if (_columnCount != null) {
                  _columnCount = null;
                } else {
                  _columnCount = 50;
                }
              });
            },
            child: Text(
                'Make columns ${_columnCount == null ? 'fixed' : 'infinite'}')),
        SizedBox.square(
          dimension: 10,
        ),
        Text(
          'Row count is ${_rowCount == null ? 'infinite' : '50  '}',
          style: const TextStyle(fontStyle: FontStyle.italic),
        ),
        FilledButton(
          onPressed: () {
            setState(() {
              if (_rowCount != null) {
                _rowCount = null;
              } else {
                _rowCount = 50;
              }
            });
          },
          child: Text(
            'Make rows ${_rowCount == null ? 'fixed' : 'infinite'}',
          ),
        ),
      ],
    );
  }

  TableViewCell _buildCell(BuildContext context, TableVicinity vicinity) {
    final Color boxColor =
        switch ((vicinity.row.isEven, vicinity.column.isEven)) {
      (true, false) || (false, true) => Colors.white,
      (false, false) => Colors.indigo[100]!,
      (true, true) => Colors.indigo[200]!
    };
    return TableViewCell(
      child: ColoredBox(
          color: boxColor,
          child: Center(
            child: Text('${vicinity.column}, r: ${vicinity.row}'),
          )),
    );
  }

  TableSpan _buildSpan(int index) {
    return const TableSpan(extent: FixedTableSpanExtent(100));
  }
}
